import { isFunction, isArray } from 'lodash-es'
import { isPromise } from '../utils'

/**
 * 处理字典配置
 */
export function resolveDicts(opt) {
  if (isFunction(opt.dicts)) {
    const getDicts = opt.dicts
    opt.dicts = getDicts.dicts || []
    const i = getDicts()
    if (isPromise(i)) {
      i.then(res => {
        opt.dicts.push(...res)
      })
      opt.refreshDicts = () => {
        getDicts().then(res => {
          const length = opt.dicts.length
          opt.dicts.splice(0, length, ...res)
        })
      }
    } else if (isArray(i)) {
      opt.dicts.push(...i)
    }
  }
  return opt.dicts
}

/**
 * 处理按钮配置
 *
 * @param {function|object} button 按钮配置
 */
export function resolveButtonConfig(button) {
  button = isFunction(button) ? { handler: button } : button
  return button
}

/**
 * 控件加enter事件
 */
export function onControlsEnter(controls, cb, vm) {
  const onEnter = (e) => {
    if (e.keyCode === 13) {
      cb()
    }
  }
  controls.forEach(control => {
    if (control) {
      control.addEventListener('keyup', onEnter)
    }
  })
  if (vm) {
    vm.$once('hook:beforeDestroy', () => {
      controls.forEach(control => {
        control.removeEventListener('keyup', onEnter)
      })
    })
  }
}
